package socketDemo

import (
	"fmt"
	"net"
	"time"
	"util"
)

func StartServer() {
	fmt.Println("start tcp server")
	tcpAdd, err := net.ResolveTCPAddr("tcp", "127.0.0.1:8888")
	util.CheckError(err)
	listener, err := net.ListenTCP("tcp", tcpAdd)
	util.CheckError(err)
	fmt.Println("start...")
	for {
		fmt.Println("prepare connect...")
		conn, err := listener.Accept()
		if err != nil {
			fmt.Println(err)
			continue
		}
		go func(conn net.Conn) {
			fmt.Println("New Connect:", conn.LocalAddr())
			defer conn.Close()
			conn.SetDeadline(time.Now().Add(2 * time.Minute)) //设置2分钟超时
			request := make([]byte, 128)
			for {
				read_len, err := conn.Read(request)
				if err != nil {
					fmt.Println(err)
					break
				}
				if read_len == 0 {
					break //未读到内容，client已关闭
				}
				fmt.Println("Get Request:", string(request))
				/**
				if string(request) == "gettime" {
					n, err := conn.Write([]byte(time.Now().String()))
					fmt.Println("Send Message To Client:", n)
					if err != nil {
						fmt.Println(err)
					}
				} else {
					n, err := conn.Write(request)
					fmt.Println("Send Message To Client:", n)
					if err != nil {
						fmt.Println(err)
					}
				}**/
				n, err := conn.Write([]byte{'a', 'b'})
				fmt.Println("Send Message To Client:", n)
				if err != nil {
					fmt.Println(err)
				}
				request = make([]byte, 128) //清空已读内容
			}
		}(conn)
	}
}
